import React, { useEffect, useState, useRef } from 'react'
import { DownloadOutlined } from '@ant-design/icons'
import {
  Button,
  Col,
  Flex,
  Form,
  Input,
  Row,
  Select,
  Typography,
  Table,
  Alert,
  Modal,
  Tabs
} from 'antd'
import MyDatePicker from '../components/MyDatePicker'
import BasicInfo from '../components/BasicInfo'
import BehaviorInteraction from '../components/BehaviorInteraction'
import CustomReturn from '../components/CustomReturn'
import { userList } from '../service/user'
import moment from 'moment'
import PlatformBasicInfo from '../components/PlatformBasicInfo'

export default function UserList() {
  // 保存选择的日期范围
  const [selectedDateString, setSelectedDateString] = useState(null)
  // 保存用户列表
  const [userListData, setUserListData] = useState([])
  // 保存页码
  const [pageNo, setPageNo] = useState(1)
  // 总数据量
  const [total, setTotal] = useState(0)
  // 表格中选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // 表格中是否有选中
  const hasSelected = selectedRowKeys.length > 0
  // 创建表单的引用
  const formRef = useRef()
  // 模态框状态
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isModalOpen2, setIsModalOpen2] = useState(false)
  // 搜索条件
  const [condition, setCondition] = useState({})
  // 用于更新列表的触发器
  const [refreshTrigger, setRefreshTrigger] = useState(1)

  // 请求用户列表数据
  const fetchUserList = async () => {
    // 构建查询参数，合并基础条件和分页信息
    const params = {
      ...condition,
      pageNo,
      pageSize: 10
    }

    // 处理日期范围查询参数
    if (selectedDateString && selectedDateString.length === 2) {
      params.startTime = selectedDateString[0]
      params.endTime = selectedDateString[1]
    }

    try {
      const res = await userList(params)
      console.log('用户列表数据:', res)
      if (res.data) {
        setUserListData(res.data.objects || [])
        setTotal(res.data.total || 0)
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
    }
  }

  // 当查询条件、页码或刷新触发器变化时重新获取数据
  useEffect(() => {
    fetchUserList()
  }, [refreshTrigger, pageNo])

  // 处理查询表单提交
  const handleSearch = async (values) => {
    // 重置页码为第一页
    setPageNo(1)

    // 构建查询条件对象
    const newCondition = {
      // 用户姓名查询条件
      ...(values.storeName && { userName: values.storeName }),
      // 手机号查询条件
      ...(values.storeHeadPhone && { phone: values.storeHeadPhone }),
      // 渠道来源查询条件
      ...(values.storeAddress && values.storeAddress !== '' && { providerType: values.storeAddress })
    }

    // 更新查询条件
    setCondition(newCondition)
    // 触发列表刷新
    setRefreshTrigger(prev => prev + 1)
  }

  // 处理重置按钮
  const handleReset = () => {
    // 重置表单
    formRef.current?.resetFields()
    // 清除日期选择
    setSelectedDateString(null)
    // 重置页码
    setPageNo(1)
    // 清除查询条件
    setCondition({})
    // 触发列表刷新
    setRefreshTrigger(prev => prev + 1)
  }

  return (
      <>
        <Row className="info">
          <Col span={24}>
            <Flex justify={'space-between'}>
              <Typography.Title level={3}>信息管理</Typography.Title>
            </Flex>
          </Col>
        </Row>

        <Row className="container">
          <Col span={24}>
            <Form
                ref={formRef}
                layout="inline"
                onFinish={handleSearch}
                initialValues={{ storeAddress: '' }}
            >
              <Form.Item label="用户姓名：" name="storeName">
                <Input placeholder="请输入用户姓名" />
              </Form.Item>
              <Form.Item label="手机号：" name="storeHeadPhone">
                <Input type="tel" placeholder="请输入手机号" />
              </Form.Item>
              <Form.Item label="渠道来源：" name="storeAddress">
                <Select
                    style={{ width: 200 }}
                    placeholder="渠道选择"
                    options={[
                      { value: '', label: '全部' },
                      { value: '0', label: 'APP' },
                      { value: '1', label: '小程序' },
                      { value: '2', label: '支付宝生活号' }
                    ]}
                />
              </Form.Item>
              <Form.Item label="注册时间">
                <MyDatePicker
                    selectedDateString={selectedDateString}
                    setSelectedDateString={setSelectedDateString}
                    placeholder={['开始日期', '结束日期']}
                />
              </Form.Item>

              <Form.Item>
                <Button type="default" onClick={handleReset}>
                  重置
                </Button>
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>

        <Row className="container">
          <Col span={24}>
            <Typography.Paragraph style={{ fontSize: 16 }}>
              用户列表
            </Typography.Paragraph>
            {hasSelected && (
                <Alert
                    message={`已经选择 ${selectedRowKeys.length} 项`}
                    type="info"
                    showIcon
                />
            )}
          </Col>

          <Col span={24}>
            <Table
                pagination={{
                  total,
                  current: pageNo,
                  pageSize: 10,
                  showSizeChanger: false,
                  onChange: (page) => {
                    setPageNo(page)
                  }
                }}
                rowKey="id"
                rowSelection={{
                  selectedRowKeys,
                  onChange: (newSelectedRowKeys) => {
                    setSelectedRowKeys(newSelectedRowKeys)
                  }
                }}
                dataSource={userListData}
                columns={[
                  {
                    title: '编号',
                    dataIndex: 'id',
                    key: 'id'
                  },
                  {
                    title: '昵称',
                    dataIndex: 'userName',
                    key: 'userName'
                  },
                  {
                    title: '性别',
                    dataIndex: 'sex',
                    key: 'sex',
                    render: (text) => text === 1 ? '男' : '女'
                  },
                  {
                    title: '手机号',
                    dataIndex: 'phone',
                    key: 'phone'
                  },
                  {
                    title: '账号',
                    dataIndex: 'userName',
                    key: 'userName'
                  },
                  {
                    title: '用户标签',
                    key: 'tags',
                    render: (_, record) => {
                      return <a>查看（5）</a>
                    }
                  },
                  {
                    title: '注册渠道',
                    dataIndex: 'providerType',
                    key: 'providerType',
                    render: (type) => {
                      switch (type) {
                        case 0: return 'APP'
                        case 1: return '小程序'
                        case 2: return '支付宝生活号'
                        default: return '未知'
                      }
                    }
                  },
                  {
                    title: '最近登录时间',
                    dataIndex: 'lastLogTime',
                    key: 'lastLogTime',
                    render: (time) => time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '从未登录'
                  },
                  {
                    title: '注册时间',
                    dataIndex: 'regTime',
                    key: 'regTime',
                    render: (time) => time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : ''
                  },
                  {
                    title: '操作',
                    key: 'op',
                    align: 'center',
                    render: (_, record) => {
                      return (
                          <a
                              onClick={() => {
                                setIsModalOpen2(true)
                              }}
                          >
                            详情
                          </a>
                      )
                    }
                  }
                ]}
            />
          </Col>
        </Row>

        <Modal
            title="用户详情"
            open={isModalOpen}
            onCancel={() => setIsModalOpen(false)}
            maskClosable={false}
            width={750}
            destroyOnClose
            footer={null}
        >
          <Tabs
              style={{ paddingBottom: 20, height: 600 }}
              items={[
                {
                  key: '1',
                  label: '基本信息',
                  children: <BasicInfo />
                },
                {
                  key: '2',
                  label: '行为互动',
                  children: <BehaviorInteraction />
                },
                {
                  key: '3',
                  label: '客户回访',
                  children: <CustomReturn />
                }
              ]}
          />
        </Modal>

        <Modal
            title="用户详情"
            open={isModalOpen2}
            onCancel={() => setIsModalOpen2(false)}
            maskClosable={false}
            width={750}
            destroyOnClose
            footer={null}
        >
          <Tabs
              style={{ paddingBottom: 20, height: 470 }}
              items={[
                {
                  key: '1',
                  label: '基本信息',
                  children: <PlatformBasicInfo />
                }
              ]}
          />
        </Modal>
      </>
  )
}
